package top.kaoshanji.p2ch14a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码清单-p2ch14a-397页a：使用BasicDB
 * @see top.kaoshanji.p2ch14a.BasicDB
 * author kaoshanji
 * ^_^
 * create time 2025/2/21 17:30
 */
public class StudentDB {

    private static final Logger logger = LogManager.getLogger(StudentDB.class);

    private static final String pathRoot = FileConstant.LOCAL_ROOT_PATH.concat("p2ch14a397页a\\");

    public static void main(String[] args) throws IOException {

        // saveStudents();

        getStudent("s3");

    }

    // 保存对象
    public static void saveStudents() throws IOException {

        Map<String, Student> studentMap = new HashMap<>(3);
        studentMap.put("s1", new Student("吕布", 22, 1.2d));
        studentMap.put("s2", new Student("曹操", 34, 3.3d));
        studentMap.put("s3", new Student("鲁班", 7, 2.3d));

        BasicDB db = new BasicDB(pathRoot , "students");

        for (Map.Entry<String, Student> kv : studentMap.entrySet()) {
            db.put(kv.getKey(), toBytes(kv.getValue()));
        }

        db.close();
    }

    // 获取指定键的值
    public static void getStudent(String key) throws IOException {
        BasicDB db = new BasicDB(pathRoot , "students");

        byte[] bytes = db.get(key);
        String value = new String(bytes);

        logger.info("...键:{}...对应的值:{}...", key, value);
    }

    // 这个转换的过程有些繁琐
    private static byte[] toBytes(Student student) throws IOException {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        DataOutputStream dout = new DataOutputStream(bout);
        dout.writeUTF(student.getName());
        dout.writeInt(student.getAge());
        dout.writeDouble(student.getScore());

        return bout.toByteArray();
    }


}
